package com.iguo.news.controller;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.iguo.news.entity.*;
import com.iguo.news.mapper.NewMapper;
import com.iguo.news.service.impl.NewScoreServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

@RequestMapping("/newScore")
@RestController
@CrossOrigin
@Slf4j
public class NewScoreController {


  @Autowired
  NewScoreServiceImpl newScoreService;

  @Autowired
  NewMapper newMapper;

  @GetMapping("/findScore")
  public R<Integer> findScore(@RequestParam("userId") String userId, @RequestParam("newId") String newId) {

    LambdaQueryWrapper<NewScore> wrapper = new LambdaQueryWrapper<>();
    wrapper.eq(NewScore::getUserId,userId);
    wrapper.eq(NewScore::getNewId,newId);
    NewScore one = newScoreService.getOne(wrapper);

    if(one == null)
      return R.success(0);
    System.out.println("findScore "+userId+" "+newId+ " " +one.getScore());
    return R.success(one.getScore());
  }

  @GetMapping("/userScoredNew")
  public R<List<NewWithScore>> userScoredNum(@RequestParam("userId") Integer userId){
    System.out.println("userId: " + userId);
    return R.success(newScoreService.getNewWithScoreByUserId(userId));
  }

  @DeleteMapping("/deleteScore")
  public R<String> deleteScore(Integer id){
    boolean b = newScoreService.deleteById(id);
    if(b) {
      return R.success("删除成功");
    }
    return R.error("删除失败");
  }

  /**
   * 用户评分
   * @param newScore
   * @return
   */
  @PutMapping("/updateScore")
  public R<String> updateScore(@RequestBody NewScore newScore) {
    System.out.println(newScore.toString());
    newScore.setTime(LocalDateTime.now());
    boolean isTrue = newScoreService.updateScore(newScore);
    if(isTrue){
      return R.success("评分成功");
    }
    return R.error("评分失败");
  }

  @GetMapping("/recommend")
  public R<List<New>> recommendBook(@RequestParam String userId) {
    //获取当前用户的点赞列表
    LambdaQueryWrapper<NewScore> queryWrapper = new LambdaQueryWrapper<>();
    queryWrapper.eq(NewScore::getUserId,userId);
    List<NewScore> newScoreList = newScoreService.list(queryWrapper);
    //查询新闻前12条数据
    LambdaQueryWrapper<New> wrapper = new LambdaQueryWrapper<>();
    wrapper.orderBy(true,true,New::getId);
    wrapper.last("LIMIT 12");
    //如果查询到的点赞列表为空，就默认返回新闻数据的前12条
    if(newScoreList.isEmpty()) {
      List<New> news = newMapper.selectList(wrapper);
      return R.success(news);
    }else {
      //返回推荐的书
      List<New> list = newScoreService.recommend(userId);
      if(list.isEmpty()){
        //如果推荐列表也是空，就返回前12本
        List<New> news = newMapper.selectList(wrapper);
        return R.success(news);
      }else {
        return R.success(list);
      }
    }
  }
}
